package cn.sharp.bbs.controller.msg;

import cn.sharp.bbs.common.Result;
import cn.sharp.bbs.entity.BO.CurrentUser;
import cn.sharp.bbs.entity.DO.Lettercontent;
import cn.sharp.bbs.service.ChatService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 私信的请求控制器
 * @author zhao yu
 */
@RestController
@RequestMapping("/chat")
public class ChatController {

    @Resource
    private ChatService chatService;

    /**
     * 获得聊天室id，如果没有，则创建
     * @param user
     * @return
     */
    @PostMapping("/getroom/{id}")
    private Result getChatRoom(@RequestAttribute("CurrentUser") CurrentUser user,
                               @PathVariable("id") Long id){
        return Result.success(chatService.getChatRoom(id, user.getU_id()));
    }

    /**
     * 获得聊天室列表
     * @param user
     * @return
     */
    @GetMapping("/roomList")
    private Result getChatRoomList(@RequestAttribute("CurrentUser") CurrentUser user){
        return Result.success(chatService.getChatRoomList(user.getU_id()));
    }

    /**
     * 获得聊天历史（聊天室记录）
     * @return 聊天信息列表
     */
    @GetMapping("/room/{user}")
    public Result getChatHistory(@PathVariable("user") Long one,
                                 @RequestAttribute("CurrentUser") CurrentUser user) {
        try {
            return Result.success(chatService.getChatHistory(one, user.getU_id()));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(Result.ERR_CODE_BUSINESS, "发送失败！");
        }
    }

    /**
     * 发送私信
     * @return 是否成功
     */
    @PostMapping("/submit")
    public Result submitChat(@RequestBody Lettercontent lettercontent,
                             @RequestAttribute("CurrentUser") CurrentUser user) {
        chatService.submit(lettercontent, user.getU_id());
        return Result.success();
    }
}
